import axios from "axios";
import { getToken,removeToken } from "@/composables/cookie";
import { showMessage } from "@/composables/util";
import { useUserStore } from "@/stores/user"
/**
 * 创建axios实例
 */
const instance = axios.create({
    baseURL: '/api',//API的基础路径
    timeout: 10000//请求超时时间
})
/**
 * 请求拦截器
 */
instance.interceptors.request.use(config => {
    //如果不是后台管理请求 则不需要携带token
    if(config.url.indexOf('/admin') === -1){
        return config
    }
    const token = getToken()
    if(token){
        config.headers.Authorization = 'Bearer ' + token
    }
    return config
}, error => {
    return Promise.reject(error)
})
/**
 * 响应拦截器
 */
instance.interceptors.response.use(response => {
    return response.data
}, function(error) {
    let status = error.response.status
    console.log(status === 401)
    // 状态码 401
    if (status === 401) {
        // 退出登录
        let userStore = useUserStore()
        userStore.logout()
        // 刷新页面
        location.reload()
    }
    let errorMsg = error.response.data.message || '请求失败'
    showMessage(errorMsg, 'error')
    return Promise.reject(error)
})

export default instance